package com.heyqing.medium.day3;

import java.util.*;

/**
 * ClassName:IntToRoman
 * Package:com.heyqing.medium.day3
 * Description:
 *
 * @Date:2024/10/4
 * @Author:Heyqing
 */
public class IntToRoman {

    /**
     * I    V   X   L   C   D   M
     * 1    5   10  50  100 500 1000
     * IV   IX  XL  XC  CD  CM
     * 4    9   40  90  400 90
     *
     * @param num
     * @return
     */
    public String intToRoman(int num) {
        List<String> list = new ArrayList<>();
        Map<Integer, String> resource = generateMap();
        int count = 0;
        while (num > 0) {
            int t = (num % 10) * (int) Math.pow(10, count);
            String str = resource.get(t);
            if (!Objects.isNull(str)) {
                list.add(str);
            } else {
                StringBuilder sb = new StringBuilder();
                while (t > 0) {
                    String s = resource.get(t);
                    if (!Objects.isNull(s)) {
                        sb.append(s);
                        break;
                    } else {
                        sb.append(resource.get((int) Math.pow(10, count)));
                    }
                    t -= (int) Math.pow(10, count);
                }
                list.add(sb.reverse().toString());
            }
            num /= 10;
            count++;
        }
        StringBuilder res = new StringBuilder();
        for (int i = list.size() - 1; i >= 0; i--) {
            res.append(list.get(i));
        }
        return res.toString();
    }

    private Map<Integer, String> generateMap() {
        return new HashMap<>() {{
            put(1, "I");
            put(5, "V");
            put(10, "X");
            put(50, "L");
            put(100, "C");
            put(500, "D");
            put(1000, "M");
            put(4, "IV");
            put(9, "IX");
            put(40, "XL");
            put(90, "XC");
            put(400, "CD");
            put(900, "CM");
        }};
    }
}
